package com.lixin.smartclassroom.ui.home.tab5.activity

import android.content.Context
import android.os.Environment
import android.util.Log
import com.drake.brv.utils.bindingAdapter
import com.drake.net.Get
import com.drake.net.component.Progress
import com.drake.net.interfaces.ProgressListener
import com.drake.net.utils.scopeNetLife
import com.lixin.smartclassroom.api.deletefolder
import com.lixin.smartclassroom.api.folderlist
import com.lixin.smartclassroom.bean.DataListBean
import com.lixin.smartclassroom.common.addDatabaseDialog
import com.lixin.smartclassroom.common.saveSuccessDialog
import com.lixin.smartclassroom.databinding.ActivityDatabaseDetailBinding
import com.lixin.smartclassroom.ui.home.adapter.databaseDetail
import com.lixinkeji.base.BaseActivity
import com.lixinkeji.extension.commonDialog
import com.lixinkeji.extension.getIntentString
import com.lixinkeji.extension.gone
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.removeAt
import com.lixinkeji.extension.toast
import com.lixinkeji.extension.visible
import com.lixinkeji.utils.SaveUtils
import java.io.File


/**
 * Description 资料库
 * Author: lwc
 * Date:2023/12/11 9:21
 */
class DatabaseDetailAct : BaseActivity<ActivityDatabaseDetailBinding>() {
    override fun getViewBinding() = ActivityDatabaseDetailBinding.inflate(layoutInflater)

    override fun topBarHide() = false
    override fun startPadding() = true
    override fun title() = "资料库"
    private lateinit var listBean: ArrayList<DataListBean>
    private var pid = ""

    override fun iniView() {
        pid = getIntentString("pid")
        binding.recycler.databaseDetail().apply {

        }

        binding.apply {
            refresh.onRefresh {
                scopeNetLife {
                    listBean = folderlist(index, 10, "2", pid)!!
                    addData(listBean) {
                        if (binding.recycler.bindingAdapter.models?.size == 0) {
                            binding.state.showEmpty()
                            binding.recycler.gone()
                            llBottom.gone()

                        } else {
                            binding.recycler.visible()
                            llBottom.visible()
                        }
                        listBean.size == 10
                    }
                }
            }.autoRefresh()
        }
    }


    override fun onClick() {
        binding.btnAdd.onClick {
            this.addDatabaseDialog()
        }
        binding.btnDownload.onClick {
            downloadData()
        }
        binding.btnDelete.onClick {
            if (binding.recycler.bindingAdapter.getCheckedModels<DataListBean>().isEmpty()) {
                toast("请选择您要删除的文件")
            } else {
                commonDialog("删除文件夹",
                    content = "删除后，所有数据将会清空\n且不可恢复，请谨慎操作",
                    cancel = "取消",
                    sure = "删除",
                    onSure = {
                        deleteData()
                    })
            }

        }
    }

    private fun downloadData() {
        binding.apply {
            scopeNetLife {
                if (recycler.bindingAdapter.checkedCount == 0) {
                    toast("请选择您要下载的文件")
                } else {
                    llProgress.visible()
                    scopeNetLife {
                        val file =
                            Get<File>((recycler?.bindingAdapter?.models?.get(recycler.bindingAdapter.checkedPosition[0]) as DataListBean).url!!) {
                                setDownloadFileName(
                                    "smartclass" + (recycler?.bindingAdapter?.models?.get(
                                        recycler.bindingAdapter.checkedPosition[0]
                                    ) as DataListBean).title!!
                                )
//                                setDownloadDir(getFilesPath(this@DatabaseDetailAct)!!)
                                setDownloadDir(getFilesPath(this@DatabaseDetailAct)!!)
                                Log.e(
                                    "-------------",
                                    "downloadData: " + Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DCIM
                                    ).absolutePath
                                )
                                setDownloadMd5Verify()
                                addDownloadListener(object : ProgressListener() {
                                    override fun onProgress(p: Progress) {
                                        binding.seekBar?.post {
                                            val progress = p.progress()
                                            seekBar.progress = progress
                                            tvProgress.text =
                                                "下载进度: $progress% 下载速度: ${p.speedSize()}     " +
                                                        "\n\n文件大小: ${p.totalSize()}  已下载: ${p.currentSize()}  剩余大小: ${p.remainSize()}" +
                                                        "\n\n已使用时间: ${p.useTime()}  剩余时间: ${p.remainTime()}"
                                        }
                                    }
                                })
                            }.await()
                        saveSuccessDialog("下载成功")
                        llProgress.gone()
                        if (file.path.endsWith(".mp4"))
                            SaveUtils.saveVideoToAlbum(this@DatabaseDetailAct, file.path)
                        else
                            SaveUtils.saveImgFileToAlbum(this@DatabaseDetailAct, file.path)
                    }
                }
            }
        }
    }

    private fun deleteData() {
        binding.apply {
            scopeNetLife {
                if (recycler.bindingAdapter.checkedCount == 0) {
                    toast("请选择您要删除的文件")
                } else {
                    deletefolder((recycler?.bindingAdapter?.models?.get(recycler.bindingAdapter.checkedPosition[0]) as DataListBean).id!!)
                    saveSuccessDialog("删除成功")
                    binding.recycler.bindingAdapter.removeAt(recycler.bindingAdapter.checkedPosition[0])
                }
            }
        }
    }

    private fun getFilesPath(context: Context): String? {
//        val filePath: String =
//            if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() || !Environment.isExternalStorageRemovable()) {
//                //外部存储可用
//                context.getExternalFilesDir(null)?.path!!
//            } else {
//                //外部存储不可用
//                context.filesDir.path
//            }


        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).absolutePath
    }


}